package io.github.lee.core.ui.ba

import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.view.View
import android.view.ViewGroup
import androidx.annotation.ColorInt
import androidx.databinding.BindingAdapter
import io.github.lee.core.util.toPx

@BindingAdapter(value = ["gone"], requireAll = false)
fun View.gone(gone: Boolean) {
    if (gone) {
        this.visibility = View.GONE
    } else {
        this.visibility = View.VISIBLE
    }
}

@BindingAdapter(value = ["invisible"], requireAll = false)
fun View.invisible(invisible: Boolean) {
    if (invisible) {
        this.visibility = View.INVISIBLE
    } else {
        this.visibility = View.VISIBLE
    }
}

@BindingAdapter(
    value = ["color", "border_width", "border_color",
        "corner_left_top", "corner_right_top",
        "corner_left_bottom", "corner_right_bottom", "corner_all"], requireAll = false
)
fun View.setGradientDrawable(
    @ColorInt color: Int?,
    borderWidth: Float?, @ColorInt borderColor: Int?,
    lt: Float?,
    rt: Float?,
    lb: Float?,
    rb: Float?,
    all: Float?
) {
    val d = if (null != all) {
        createGradientDrawable(color ?: Color.TRANSPARENT,
            all.toPx(context).toFloat(), all.toPx(context).toFloat(),
            all.toPx(context).toFloat(), all.toPx(context).toFloat())
    } else {
        createGradientDrawable(color ?: Color.TRANSPARENT, lt ?: 0F, rt ?: 0F, lb ?: 0F, rb ?: 0F)
    }
    if (null != borderWidth || null != borderColor) {
        d.setStroke(borderWidth?.toPx(context) ?: 0, borderColor ?: Color.TRANSPARENT)
    }
    this.background = d
}

fun createGradientDrawable(
    @ColorInt color: Int,
    lt: Float,
    rt: Float,
    lb: Float,
    rb: Float
): GradientDrawable {
    val gd = GradientDrawable()
    gd.setColor(color)
    gd.cornerRadii = floatArrayOf(
        lt, lt,
        rt, rt,
        lb, lb,
        rb, rb
    )
    return gd
}

val View.parentViewGroup: ViewGroup?
    get() {
        val parent = parent
        return if (parent is ViewGroup) {
            parent
        } else {
            null
        }
    }

fun View.removeFromParent() {
    this.parentViewGroup?.removeView(this)
}
